package com.kb.design.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.design.constant.Constants;
import com.kb.design.dto.DesignRequirementDTO;
import com.kb.design.dto.ForestallOrderDTO;
import com.kb.design.dto.TaskCompletedDTO;
import com.kb.design.entity.*;
import com.kb.design.enums.DesignStatus;
import com.kb.design.enums.ProjectStatus;
import com.kb.design.enums.ReviewType;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CustomUserService;
import com.kb.design.service.DesignRequirementServer;
import com.kb.design.service.DesignReviewService;
import com.kb.design.util.CommonUtil;
import com.kb.design.vo.ReviewVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther:chenzx
 * @Date:2023/11/13
 * @Description:
 */
@Service
@DS("slave-1")
public class DesignRequirementImpl implements DesignRequirementServer {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(DesignRequirementImpl.class);
    @Autowired
    private DesignRequirementMapper designRequirementMapper;
    @Resource
    private ProjectServiceImpl projectServiceImpl;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private WorkTimeMapper workTimeMapper;
    @Resource
    private DesignDictDataMapper designDictDataMapper;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;
    @Resource
    private CustomUserService userService;
    @Resource
    private DesignFileMapper designFileMapper;
    @Resource
    private DesignReviewService designReviewService;
    @Resource
    private CustomUserMapper userMapper;

    @Override
    public Page<DesignRequirementDTO> queryByPage(DesignRequirementDTO designRequirementDTO) {
        Page<DesignRequirementDTO> page = new Page<>(designRequirementDTO.getPage(), designRequirementDTO.getPerPage());
        //数据权限 查询权限
        CustomUser customUser = userMapper.queryUser(designRequirementDTO.getCreateBy());
        if (Objects.isNull(customUser)){
            log.info("请先在用户页面新建当前登录人账号: {}", designRequirementDTO.getCreateBy());
            return null;
        }

            List<UserSecurity> userSecurityList = userMapper.queryUserSecurity(designRequirementDTO.getCreateBy());
            if (CollectionUtil.isNotEmpty(userSecurityList)){
                List<String> integerList = userSecurityList.stream()
                        .map(UserSecurity::getUserCode)
                        .collect(Collectors.toList());
                designRequirementDTO.setUserCodeList(integerList);
            }

        return responsiblePersonMapper.queryDesignPage(page, designRequirementDTO);
    }

    @Override
    public boolean forestallOrder(ForestallOrderDTO forestallOrderDTO) {
        CommonUtil.webLog("DesignRequirementImpl.forestallOrder", forestallOrderDTO);

        //根据工号查询name
//        String userName = userService.queryNickName(forestallOrderDTO.getNodeResponsiblePersonId());

        DesignRequirement designRequirement = new DesignRequirement();
        designRequirement.setId(forestallOrderDTO.getId());
        designRequirement.setNodeResponsiblePersonId(forestallOrderDTO.getUserId());
//        designRequirement.setNodeResponsiblePersonName(userName);

//        designRequirement.setDesignStatus(DesignStatus.LAYOUT.getIndex());
        designRequirement.setUpdateTime(LocalDateTime.now());
        designRequirementMapper.updateById(designRequirement);

        //状态流转
//        DesignStatusTransfer designStatusTransfer = new DesignStatusTransfer();
//        designStatusTransfer.setStatus(ProjectStatus.APPOINT.getIndex());
//        designStatusTransfer.setTitle(ProjectStatus.APPOINT.getName());
//        designStatusTransfer.setProjectId(forestallOrderDTO.getProjectId());
//        designStatusTransfer.setColor(ProjectStatus.APPOINT.getColor());

//        projectServiceImpl.insertStatusTransfer(designStatusTransfer);

        //修改项目表里面的任务状态
        projectServiceImpl.updateProjectTaskStatus(DesignStatus.DESIGN.getIndex(), forestallOrderDTO.getProjectId(),"");
        return true;
    }

    @Override
    public boolean submitLayout(ForestallOrderDTO forestallOrderDTO) {
        CommonUtil.webLog("DesignRequirementImpl.submitLayout", forestallOrderDTO);
//        boolean b = insetResponsiblePerson(forestallOrderDTO, DesignStatus.WIRING.getIndex());
        if (Objects.equals("1",forestallOrderDTO.getParentId())){
            return true;
        }
        //更新设计主表信息
        DesignRequirement designRequirement = new DesignRequirement();
        designRequirement.setId(forestallOrderDTO.getId());
        designRequirement.setNodeResponsiblePersonId(forestallOrderDTO.getNodeResponsiblePersonId());

        //到布线
//        designRequirement.setDesignStatus(DesignStatus.WIRING.getIndex());
        //审批状态  需要去查是否审批
        designRequirement.setReviewType(designReviewService.queryReviewStatus(forestallOrderDTO.getProjectId()));
        designRequirementMapper.updateById(designRequirement);

        //状态流转
//        DesignStatusTransfer designStatusTransfer = new DesignStatusTransfer();
//        designStatusTransfer.setStatus(ProjectStatus.LAYOUT.getIndex());
//        designStatusTransfer.setTitle(ProjectStatus.LAYOUT.getName());
//        designStatusTransfer.setProjectId(forestallOrderDTO.getProjectId());
//        designStatusTransfer.setColor(ProjectStatus.LAYOUT.getColor());
//
//        projectServiceImpl.insertStatusTransfer(designStatusTransfer);

        //修改项目表里面的任务状态
//        projectServiceImpl.updateProjectTaskStatus(DesignStatus.WIRING.getIndex(), forestallOrderDTO.getProjectId(),forestallOrderDTO.getNodeResponsiblePersonId());
        //保存负责人信息到design_responsible_person表

        return true;
    }

    private boolean insetResponsiblePerson(ForestallOrderDTO forestallOrderDTO,String nodeStatus) {
        //更新本节点信息   design_responsible_person的备注信息（设计详情信息）
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
        designResponsiblePerson.setRemark(forestallOrderDTO.getRemark());
//        designResponsiblePerson.setCommonId(forestallOrderDTO.getId());
        designResponsiblePerson.setIsComplete(Constants.YES_COMPLETE);
        LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignResponsiblePerson::getProjectId, forestallOrderDTO.getProjectId())
                .eq(DesignResponsiblePerson::getNodeStatus,forestallOrderDTO.getStatus());
        responsiblePersonMapper.update(designResponsiblePerson, queryWrapper);
        //附件 先删 后增
        if (StringUtils.isNotBlank(forestallOrderDTO.getUrl())){
            DesignFile designFile = new DesignFile();
            LambdaQueryWrapper<DesignFile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DesignFile::getDesignId, forestallOrderDTO.getId())
                    .eq(DesignFile::getType,forestallOrderDTO.getStatus());
            designFileMapper.delete(wrapper);
            designFile.setDesignId(forestallOrderDTO.getId());
            designFile.setType(forestallOrderDTO.getStatus());
            designFile.setUrl(forestallOrderDTO.getUrl());
            designFileMapper.insert(designFile);
        }

        //新增下一节点数据
        BeanUtils.copyProperties(forestallOrderDTO, designResponsiblePerson);
//        designResponsiblePerson.setNodeResponsiblePersonId(forestallOrderDTO.getNodeResponsiblePersonId());
        designResponsiblePerson.setNodeStatus(nodeStatus);
        designResponsiblePerson.setDel(Constants.DEL_FLAG_NO)
                .setProjectId(forestallOrderDTO.getProjectId())
                .setId(null)
                .setRemark(null);
        responsiblePersonMapper.insert(designResponsiblePerson);
        return true;
    }

    /**
     * 布线
     * @param forestallOrderDTO
     * @return
     */
    @Override
    public boolean submitWiring(ForestallOrderDTO forestallOrderDTO) {
        CommonUtil.webLog("DesignRequirementImpl.submitWiring", forestallOrderDTO);

        //根据工号查询name
//        String userName = userService.queryNickName(forestallOrderDTO.getNodeResponsiblePersonId());

        DesignRequirement designRequirement = new DesignRequirement();
        designRequirement.setId(forestallOrderDTO.getId());

        designRequirement.setNodeResponsiblePersonId(forestallOrderDTO.getNodeResponsiblePersonId());
        //查询是否审批
        designRequirement.setReviewType(designReviewService.queryReviewStatus(forestallOrderDTO.getProjectId()));
        //布线完成审批
//        designRequirement.setDesignStatus(DesignStatus.ACCEPTANCE.getIndex());
        designRequirementMapper.updateById(designRequirement);

        //状态流转
//        DesignStatusTransfer designStatusTransfer = new DesignStatusTransfer();
//        designStatusTransfer.setStatus(ProjectStatus.WIRING.getIndex());
//        designStatusTransfer.setTitle(ProjectStatus.WIRING.getName());
//        designStatusTransfer.setProjectId(forestallOrderDTO.getProjectId());
//        designStatusTransfer.setColor(ProjectStatus.WIRING.getColor());

//        projectServiceImpl.insertStatusTransfer(designStatusTransfer);

        //修改项目表里面的任务状态
        projectServiceImpl.updateProjectTaskStatus(DesignStatus.DESIGN.getIndex(), forestallOrderDTO.getProjectId(),forestallOrderDTO.getNodeResponsiblePersonId());

        //保存负责人信息到design_responsible_person表
        return insetResponsiblePerson(forestallOrderDTO,DesignStatus.DESIGN.getIndex());
//        return true;
    }

    @Override
    public boolean fallback(ForestallOrderDTO forestallOrderDTO) {
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
        //新增流程子表
        BeanUtils.copyProperties(forestallOrderDTO, designResponsiblePerson);
        designResponsiblePerson.setDel(Constants.DEL_FLAG_NO)
                .setIsComplete(Constants.NO_COMPLETE)
                .setId(null);
        responsiblePersonMapper.insert(designResponsiblePerson);


        /**
         * 更新任务主表
         */
        DesignRequirement designRequirement = new DesignRequirement();
        designRequirement.setId(forestallOrderDTO.getRequirementId());

        designRequirement.setNodeResponsiblePersonId(forestallOrderDTO.getNodeResponsiblePersonId());
        designRequirement.setDesignStatus(forestallOrderDTO.getNodeStatus());
        designRequirement.setReviewType(ReviewType.Unaudited.getValue());
        designRequirementMapper.updateById(designRequirement);

        return true;
    }

    @Override
    public DesignResponsiblePerson queryAssistTask(ForestallOrderDTO forestallOrderDTO) {
        LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(DesignResponsiblePerson::getIsComplete, Constants.YES_COMPLETE)
                .last("limit 1");
        return responsiblePersonMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String,Object> queryWorkTimeList(ForestallOrderDTO forestallOrderDTO) {
        LambdaQueryWrapper<DesignResponsiblePerson> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignResponsiblePerson::getProjectId,forestallOrderDTO.getProjectId())
        .eq(DesignResponsiblePerson::getIsComplete,Constants.YES_COMPLETE);
        List<DesignResponsiblePerson> designResponsiblePersonList = responsiblePersonMapper.selectList(queryWrapper);

        // 计算 totalWorkHours 的总和
        BigDecimal sumWorkHours = BigDecimal.ZERO;

        // 计算 totalWorkHours 的总和
//        for (DesignResponsiblePerson person : designResponsiblePersonList) {
//            if (Objects.nonNull(person.getTotalWorkHours())){
//                sumWorkHours = sumWorkHours.add(person.getTotalWorkHours());
//            }
//        }
//        BigDecimal finalSumWorkHours = sumWorkHours;
//        designResponsiblePersonList.forEach(e ->{
//            e.setNodeName(DesignStatus.getName(e.getNodeStatus()));
//            e.setSumWorkHours(finalSumWorkHours);
//        });
        HashMap<String,Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("designResponsiblePersonList",designResponsiblePersonList);




        return objectObjectHashMap;
    }

    @Override
    public boolean confirmWorkHours(Map<String,List<DesignResponsiblePerson>> map) {
        //更新工时
        Long project = null;
        List<DesignResponsiblePerson> designResponsiblePersonList = map.get("designResponsiblePersonList");
       if ( CollectionUtils.isNotEmpty(designResponsiblePersonList)){
            for (DesignResponsiblePerson designResponsiblePerson : designResponsiblePersonList) {
                project = designResponsiblePerson.getProjectId();
                responsiblePersonMapper.updateById(designResponsiblePerson);
            }

            //更新流程主表状态
           LambdaQueryWrapper<DesignRequirement> queryWrapper = Wrappers.lambdaQuery();
           queryWrapper.eq(DesignRequirement::getProjectId,project);
           DesignRequirement designRequirement = new DesignRequirement();
           designRequirement.setDesignStatus(DesignStatus.FINISH.getIndex());
           designRequirementMapper.update(designRequirement,queryWrapper);
           //更新子表验收为完成状态
           LambdaQueryWrapper<DesignResponsiblePerson> query = Wrappers.lambdaQuery();
           query.eq(DesignResponsiblePerson::getProjectId,project).eq(DesignResponsiblePerson::getNodeStatus,DesignStatus.DESIGN.getIndex());
           DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
           designResponsiblePerson.setIsComplete(Constants.YES_COMPLETE);

           responsiblePersonMapper.update(designResponsiblePerson,query);

           //更新项目表
           DesignProject designProject = new DesignProject();
           designProject.setId(project);
           designProject.setStatus(DesignStatus.DESIGN.getIndex());
           projectMapper.updateById(designProject);
        }
        return true;
    }

    @Override
    @DSTransactional
    public boolean taskCompleted(TaskCompletedDTO taskCompletedDTO) {
        CommonUtil.webLog("DesignRequirementImpl.taskCompleted", taskCompletedDTO);


        /**
         * 更新子表本条数据信息，并生成下一条节点数据
         * design_responsible_person
         */
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
        BeanUtils.copyProperties(taskCompletedDTO,designResponsiblePerson);
//        designResponsiblePerson.setRemark(taskCompletedDTO.getRemark());
//        designResponsiblePerson.setCommonId(taskCompletedDTO.getId());
        designResponsiblePerson .setIsComplete(Constants.YES_COMPLETE);
        //保存不更改完成状态
        if (Objects.equals("1",taskCompletedDTO.getIsSave())){
            designResponsiblePerson .setIsComplete(Constants.NO_COMPLETE);
        }
//        if (!Objects.equals("1",taskCompletedDTO.getIsSave())){
//            //完成默认 完成率是100%
////            designResponsiblePerson.setCompletionRate(BigDecimal.valueOf(100));
//        }
        designResponsiblePerson.setUpdateTime(LocalDateTime.now());
//        designResponsiblePerson.setLastTime(LocalDateTime.now());
        //工时累加
        BigDecimal totalWorkHours = Optional.ofNullable(taskCompletedDTO.getTotalWorkHours()).orElse(BigDecimal.ZERO);
        BigDecimal actualWorkHours = Optional.ofNullable(taskCompletedDTO.getActualWorkHours()).orElse(BigDecimal.ZERO);
//        designResponsiblePerson.setTotalWorkHours(totalWorkHours.add(actualWorkHours));
//        designResponsiblePerson.setNodeResponsiblePersonId(null);
        responsiblePersonMapper.updateById(designResponsiblePerson);
        //todo 新建工时详细表
        DesignWorkTime designWorkTime = new DesignWorkTime();
        designWorkTime.setWorkTime(taskCompletedDTO.getActualWorkHours());
        designWorkTime.setCompletionRate(taskCompletedDTO.getCompletionRate());
        designWorkTime.setPersonId(taskCompletedDTO.getId());
        designWorkTime.setDesignStatus(taskCompletedDTO.getDesignStatus());
        workTimeMapper.insert(designWorkTime);
        //附件 先删 后增
        if (StringUtils.isNotBlank(taskCompletedDTO.getUrl())){
            DesignFile designFile = new DesignFile();
            LambdaQueryWrapper<DesignFile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DesignFile::getDesignId, taskCompletedDTO.getId())
                    .eq(DesignFile::getType,taskCompletedDTO.getDesignStatus());
            designFileMapper.delete(wrapper);
            designFile.setDesignId(taskCompletedDTO.getId());
            designFile.setType(String.valueOf(taskCompletedDTO.getDesignStatus()));
            designFile.setUrl(taskCompletedDTO.getUrl());
            designFileMapper.insert(designFile);
        }
        //保存 只需要到这
        if (Objects.equals("1",taskCompletedDTO.getIsSave())){
            return true;
        }
        //协同任务 不更改主表状态
        if (taskCompletedDTO.getParentId()>1){
            return true;
        }
        //新增下一节点数据 封装节点不需要新增
        if (!Objects.equals(taskCompletedDTO.getDesignStatus(),DesignStatus.ENCAPSULATION.getIndex())){
            BeanUtils.copyProperties(taskCompletedDTO, designResponsiblePerson);
//            designResponsiblePerson.setNodeResponsiblePersonId(taskCompletedDTO.getNodeResponsiblePersonId());
//            处理人名称获取
//            designResponsiblePerson.setNodeResponsiblePersonName(userService.queryNickName(taskCompletedDTO.getNodeResponsiblePersonId()));
            designResponsiblePerson.setNodeStatus(DesignStatus.getNextStatusByIndex(Integer.parseInt(taskCompletedDTO.getDesignStatus())).getIndex());
            designResponsiblePerson.setDel(Constants.DEL_FLAG_NO)
                    .setProjectId(taskCompletedDTO.getProjectId())
                    //todo 去除coyp对象
                    .setIsComplete(Constants.NO_COMPLETE)
//                    .setTotalWorkHours(null)
                    .setCompletionRate(null)
                    .setId(null)
                    .setRemark(null);
            responsiblePersonMapper.insert(designResponsiblePerson);
        }

        /**
         * 更新任务主表
         */
        DesignRequirement designRequirement = new DesignRequirement();
        designRequirement.setId(taskCompletedDTO.getRequirementId());

        designRequirement.setNodeResponsiblePersonId(taskCompletedDTO.getNodeResponsiblePersonId());

        //布线之后就开始审批
//        if (Objects.equals(taskCompletedDTO.getDesignStatus(),DesignStatus.WIRING.getIndex())){
//            designRequirement.setReviewType(ReviewType.LAYOUT_APPROVAL.getValue());
//        }
        //下一节点状态
        designRequirement.setDesignStatus(DesignStatus.getNextStatusByIndex(Integer.parseInt(taskCompletedDTO.getDesignStatus())).getIndex());
        designRequirementMapper.updateById(designRequirement);

        return true;
    }

    @Override
    public TaskCompletedDTO queryWorkData(TaskCompletedDTO taskCompletedDTO) {
        //查询
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
        designResponsiblePerson.setId(taskCompletedDTO.getId());
        DesignResponsiblePerson responsiblePerson = responsiblePersonMapper.selectById(designResponsiblePerson);
        BeanUtils.copyProperties(responsiblePerson,taskCompletedDTO);
        //附件
        LambdaQueryWrapper<DesignFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignFile::getDesignId,taskCompletedDTO.getId()).last("limit 1");
        DesignFile designFile = designFileMapper.selectOne(queryWrapper);
        if (Objects.nonNull(designFile)){
            taskCompletedDTO.setUrl(designFile.getUrl());
        }
        return taskCompletedDTO;
    }

    @Override
    public ReviewVO reviewContent(String type) {
        CommonUtil.webLog("DesignRequirementImpl.reviewContent", type);

        ReviewVO reviewVO = new ReviewVO();
        LambdaQueryWrapper<DesignDictData> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDictData::getType, type)
                .eq(DesignDictData::getStatus, "0");
        List<DesignDictData> designDictData = designDictDataMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(designDictData)) {
            Map<String, List<DesignDictData>> groupedByGrade = designDictData.stream()
                    .collect(Collectors.groupingBy(DesignDictData::getGrade));
            // 使用 getOrDefault 简化 if 判断
            reviewVO.setLayoutApproval(groupedByGrade.getOrDefault("layout_approval", Collections.emptyList()));
            reviewVO.setWiringApproval(groupedByGrade.getOrDefault("wiring_approval", Collections.emptyList()));
        }

        return reviewVO;
    }

    public static void main(String[] args) {
        System.out.println(DesignStatus.getNextStatusByIndex(25).getIndex());

    }
}
